<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : disabled ? $t('notice.view') : $t('update')"
             :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" :disabled="disabled"
             @keyup.enter="dataFormSubmitHandle()" label-width="80px">
      <el-form-item prop="name" label="指标模板">
        <el-input v-model="dataForm.name" placeholder="指标模板"></el-input>
      </el-form-item>
    </el-form>
    <template v-if="!disabled" v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from "vue";
import baseService from "@/service/baseService";
import {useI18n} from "vue-i18n";
import {ElMessage} from "element-plus";

const copyFlag = ref(false);

const saveUrl = ref("/evaluation/clcevaluationtemplate");

const {t} = useI18n();
const emit = defineEmits(["refreshDataList"]);
const disabled = ref(false);

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  name: "",
  id: ""
});

const rules = ref({
  name: [{required: true, message: t("validate.required"), trigger: "blur"}]
});

const init = (id, dis, copy) => {
  dataForm.id = "";
  visible.value = true;
  disabled.value = dis;
  if (copy) {
    copyFlag.value = copy;
    saveUrl.value = "/evaluation/clcevaluationtemplate/copy";
  }

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    dataForm.id = id;
    getInfo(id, copy);
  }
};

// 获取信息
const getInfo = (id, copy) => {
  baseService.get(`/evaluation/clcevaluationtemplate/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
    if (copy) {
      dataForm.name += "（复制）";
    }
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : copyFlag.value ? baseService.post : baseService.put)(saveUrl.value, dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init,
  dataForm
});
</script>
